import { TongXunLuData } from "../TongXunLuData";
import { friendData } from "../util/friendData";
import { GCtrl } from "../util/GCtrl";
import { groupData } from "../util/groupData";
import ChatEnum from "./ChatEnum";
const { ccclass, property } = cc._decorator;
/*
聊天消息数据管理类
*/
@ccclass
class ChatDataMgr {
    chatDataDictionary = {}; //消息字典  内存中数据
    chatfriendlist = {}; // 登录的时候 服务器传过来的好友聊天数据
    chatgrouplist = {}; // 登录的时候 服务器传过来的群聊天数据
    _softkeyhegiht = 0;
    _softkeyoffy = 0;
    SOFT_INPUT_ADJUST_RESIZE = 0x10;
    SOFT_INPUT_ADJUST_PAN = 0x20;
    SOFT_INPUT_ADJUST_NOTHING = 0x30;

    clickType = 0;

    shurukuangHeight = 150;
    zidinglanHeight = 450;
    alignBottomOne = 120;
    alignBottomTwo = 520;

    timejiange = 300 // 秒
    timeheight = 50
    timewidth = 240 // 时间lable的长度 格式 2019-01-01 12:45
    shorttimewidth = 140// 时间lable的长度 格式  12:45

    systermMessageoriginId = 99999;
    systermMessageHongBaooriginId = 99998;
    initNum = 13;
    sessionFront = "org.cocos2dx.fanpaiji";
    sessionGroupFront = "org.cocos2dx.fanpaiji_group";
    serviceArryKey = "org.cocos2dx.fanpaiji_ServiceArry";
    servicePlayerKey = "org.cocos2dx.fanpaiji_Serviceplayer";

    zhuanfadata = null;
    opendata = null; //当前打开的聊天数据
    chatViewParentNode = null;
    chatFriendlistViewParentNode = null; //聊天好友界面；
    private TongXunLuData: TongXunLuData = null;
    private newMsgData: any = {};
    private newMsgNum: number = 0;
    //---
    public quitGroupType: string = null;
    //----
    //对象池
    _ChatItemNodePool: cc.NodePool = null;
    _gameStartItemNodePool: cc.NodePool = null;
    _gamePayEndItemNodePool: cc.NodePool = null;
    _InviteOtherItemNodePool: cc.NodePool = null;
    _InviteSelfItemNodePool: cc.NodePool = null;

    //聊天消息队列
    messagedataqueue = [];  //优先队列
    LoadOfflineMsgOver: number = 1;  //1 还有数据 2 是没有数据
    startLoadOfflineMsgTimer = null;
    sendMsgToUiTimer = null;

    NATIVEPICBASE64DATA = "";
    init() {
        //1 从本地存储设备取数据 2  从网络拿数据
        cc.vv.eventCustom.on("ServerNtc", this.serverNtc.bind(this));
        cc.vv.eventCustom.on("zhuanfaMessage", this.zhuanfaMessage.bind(this));
        cc.vv.eventCustom.on("setsoftjianpanheight", this.setsoftjianpanheight.bind(this))
        cc.vv.eventCustom.on('logout', this.logout.bind(this));
        cc.vv.eventCustom.on('startgetpictureNative', this.startgetpictureNative.bind(this));
        cc.vv.eventCustom.on('pushdatapictureNative', this.pushdatapictureNative.bind(this));
        cc.vv.eventCustom.on('endgetpictureNative', this.endgetpictureNative.bind(this));

        this._ChatItemNodePool = new cc.NodePool();
        this._gameStartItemNodePool = new cc.NodePool();
        this._gamePayEndItemNodePool = new cc.NodePool();
        this._InviteOtherItemNodePool = new cc.NodePool();
        this._InviteSelfItemNodePool = new cc.NodePool();
        var fun = () => {
            if (this.messagedataqueue.length > 0) {
                let savechatData = this.messagedataqueue.shift()
                let id = Number(cc.sys.localStorage.getItem(this.sessionFront + savechatData.session)) + 1; //id 客户端维护

                if (savechatData.chat_type == ChatEnum.ChatTypeEnum.GROUP) {
                    id = Number(cc.sys.localStorage.getItem(this.sessionGroupFront + savechatData.session)) + 1 //id 客户端维护
                }
                var userData: friendData = cc.vv.TongXunLuData.getUserData(savechatData.session);
                var groupInfo: groupData = cc.vv.GroupDetailData.getGroupData(savechatData.session);
                if (cc.vv.session.getRid() != savechatData.send_id) {
                    userData && (this.setNewMsgNum(userData.Id, id - userData.readedMsgId), this.NewMsgAlert(userData));
                    groupInfo && (this.setNewMsgNum(groupInfo.Id, id - groupInfo.readedMsgId), this.NewMsgAlert(groupInfo));
                } else {
                    userData && cc.vv.TongXunLuData.setReadedMsgId(userData.Id, id);
                    groupInfo && cc.vv.GroupDetailData.setReadedMsgId(groupInfo.Id, id);
                }
                if (savechatData.contenttype == ChatEnum.DataTypeEnum.PICTURE && savechatData.originId == cc.vv.session.getRid()) {
                    cc.vv.eventCustom.emit("addChatItem", {
                        chatdata: savechatData,
                        addtop: false,
                        needScrolltobottom: true,
                        selfPic: true,
                    })
                } else {
                    cc.vv.eventCustom.emit("addChatItem", {
                        chatdata: savechatData,
                        addtop: false,
                        needScrolltobottom: true,
                    })
                }
            }
        }
        this.sendMsgToUiTimer = setInterval(fun, 50);//20毫秒检查一次messagedataqueue  往ui派发一次
    }
    startgetpictureNative() {
        this.NATIVEPICBASE64DATA = "";
    }
    pushdatapictureNative(data) {
        this.NATIVEPICBASE64DATA = this.NATIVEPICBASE64DATA.concat(data[0])
    }
    endgetpictureNative() {
        cc.vv.eventCustom.emit("getBase64dataOver");
    }

    startLoadOfflineMsg() {
        this.LoadOfflineMsgOver = 1;
        let getOneTime = () => {
            if (this.LoadOfflineMsgOver == 1 && this.messagedataqueue.length == 0) {
                cc.vv.GLUtils.sendRequest("LoadOfflineMsg", {}, (error, data) => {
                    if (!data.errorcode) {
                        this.LoadOfflineMsgOver = data.have;
                        if (this.LoadOfflineMsgOver != 1) {
                            if (this.startLoadOfflineMsgTimer) {
                                clearInterval(this.startLoadOfflineMsgTimer);
                            }
                        }
                        var senddatatemp = [];
                        if (data.msg.length > 0) {
                            for (var s = 0; s < data.msg.length; s++) {
                                var element = data.msg[s];
                                element.serverSession = element.session; //服务器记录的session  应答消息需要回复
                                element.session = this.getSessionId(element.session);
                                this.handleMessage(element);
                                if (!senddatatemp[element.serverSession]) {
                                    senddatatemp[element.serverSession] = [];
                                }
                                senddatatemp[element.serverSession].push(element.msg_seq)
                            }
                        }
                        let senddata = {
                            req: []
                        };
                        for (const key in senddatatemp) {
                            let t = {
                                session_key: key,
                                msgs_seq: senddatatemp[key],
                            }
                            senddata.req.push(t)
                        }
                        // 消息确认请求
                        if (senddata.req.length > 0) {
                            cc.vv.GLUtils.sendRequest("MsgACK", senddata, (error, data) => {
                            });
                        }
                    } else {
                        this.LoadOfflineMsgOver = data.have;
                        if (this.startLoadOfflineMsgTimer) {
                            clearInterval(this.startLoadOfflineMsgTimer);
                        }
                    }
                });
            }
        }
        this.startLoadOfflineMsgTimer = setInterval(getOneTime, 1000);//20毫秒检查一次 LoadOfflineMsgOver和messagedataqueue，两个都满足就从服务器拉一次
    }

    setRid() {
        this.sessionFront = "org.cocos2dx.fanpaiji" + "_" + cc.vv.session.getRid() + "_";
        this.sessionGroupFront = "org.cocos2dx.fanpaiji_group" + "_" + cc.vv.session.getRid() + "_";
        this.serviceArryKey = "org.cocos2dx.fanpaiji_ServiceArry" + "_" + cc.vv.session.getRid();
        this.servicePlayerKey = "org.cocos2dx.fanpaiji_Serviceplayer" + "_" + cc.vv.session.getRid() + "_";
    }
    setCurrentOpenData(data) {
        this.opendata = data;
    }
    getCurrentOpenData() {
        return this.opendata;
    }
    //获取sessionid
    getSessionId(element) {
        let arry = element.split("_")
        let selfrid = cc.vv.session.getRid();
        let sessionid = null;
        if (arry.length == 3) {
            if (arry[1] != selfrid) {
                sessionid = arry[1]
            } else {
                sessionid = arry[2]
            }
        } else {
            sessionid = arry[1]
        }
        return sessionid;
    }

    // //------------------------通知消息--------------------------
    // // 消息内容
    serverNtc(msgdata) {
        console.log("接收到服务器广播数据", msgdata)
        var data = msgdata[0]
        if (data.cmd == "MessageNtc") {
            var senddatatemp = [];
            for (var s = 0; s < data.new_msg.length; s++) {
                var element = data.new_msg[s];
                element.serverSession = element.session; //服务器记录的session  应答消息需要回复
                element.session = this.getSessionId(element.session);
                this.handleMessage(element);
                if (!senddatatemp[element.serverSession]) {
                    senddatatemp[element.serverSession] = [];
                }
                senddatatemp[element.serverSession].push(element.msg_seq)
            }
            let senddata = {
                req: []
            };
            for (const key in senddatatemp) {
                let t = {
                    session_key: key,
                    msgs_seq: senddatatemp[key],
                }
                senddata.req.push(t)
            }
            // 消息确认请求
            if (senddata.req.length > 0) {
                cc.vv.GLUtils.sendRequest("MsgACK", senddata, (error, data) => {
                });
            }
            // 群解散消息
            if (data.del_grp) {
                for (var s = 0; s < data.del_grp.length; s++) {
                    this.clearOneSessionMessage(data.del_grp[s], true)
                    cc.vv.eventCustom.emit("groupDissolve", {
                        session: data.del_grp[s],
                        group: true,
                    })
                }
            }
            // 删除好友消息
            if (data.del_fri_arr) {
                for (var s = 0; s < data.del_fri_arr.length; s++) {
                    this.clearOneSessionMessage(data.del_fri_arr[s], false)
                }
            }
            cc.vv.chatMgr.quitGroupType = null;
        }
    }

    handleMessage(element) {
        let isgroup = false;
        let id = Number(cc.sys.localStorage.getItem(this.sessionFront + element.session)) + 1; //id 客户端维护
        var localStoragekey = cc.vv.session.getRid() + "_" + element.session + "_" + id;
        if (element.chat_type == ChatEnum.ChatTypeEnum.GROUP) {
            id = Number(cc.sys.localStorage.getItem(this.sessionGroupFront + element.session)) + 1 //id 客户端维护
            localStoragekey = "group_" + cc.vv.session.getRid() + "_" + element.session + "_" + id;
            isgroup = true;
        }
        let sessionID = element.session;
        var state = ChatEnum.MessageState.NORMAL;

        let savechatData = {
            "id": id,
            "state": state,
            "time": element.timestamp,
            "content": element.data,
            "originId": element.send_id,
            "contenttype": element.data_type,
            "messagetype": element.chat_type,
            "rolename": "" || element.name,
            "url": "" || element.head,
            "session": element.session,
            "group": isgroup,  // 和上面的 chat_type 有重复  这里保持数据格式一致  调用的接口方便处理
            "Id": sessionID,
            "isService": false,
        };
        cc.vv.chatMgr.insertOneMessage(localStoragekey, savechatData, sessionID, false)
        if (element.chat_type == ChatEnum.ChatTypeEnum.CUSTOM_SVC) { //客服聊天  保存玩家的信息
            this.updateServiceRid(savechatData.originId, savechatData.rolename, savechatData.url, null)
            savechatData.isService = true;
        }
        this.messagedataqueue.push(savechatData);
    }

    //flagexlude = true  只写消息 不更新最新消息id
    insertOneMessage(key, Messagedata, sessionID, flagexlude, flagjinyan) {
        if (flagjinyan) {  // 有新的（禁言消息/未发送成功的消息）
            var newid2 = cc.sys.localStorage.getItem(this.sessionFront + Messagedata.session);
            if (Messagedata.chat_type == ChatEnum.ChatTypeEnum.GROUP) {
                newid2 = cc.sys.localStorage.getItem(this.sessionGroupFront + Messagedata.session)
            }
            var localStoragekey = cc.vv.session.getRid() + "_" + Messagedata.session + "_" + newid2;
            if (Messagedata.chat_type == ChatEnum.ChatTypeEnum.GROUP) {
                localStoragekey = "group_" + cc.vv.session.getRid() + "_" + Messagedata.session + "_" + newid2;
            }
            var newmessage = cc.sys.localStorage.getItem(localStoragekey)
            var array = JSON.parse(newmessage)

            if (!array.notSend) {
                array.notSend = [];
            }
            var savechatData = {
                "id": newid2 + "_" + (array.notSend.length + 1),
                "state": ChatEnum.MessageState.NOTSEMD,
                "time": array.time,
                "content": Messagedata.data,
                "originId": cc.vv.session.getRid(),
                "contenttype": Messagedata.data_type,
                "messagetype": Messagedata.chat_type,
                "rolename": "",//id,
                "url": "",//url,
                "session": Messagedata.session,
            };
            if (savechatData.contenttype == ChatEnum.MessageEnum.PICTURE) {
                let arry = savechatData.content.split("$")
                let url = arry[0]
                let urlarry = url.split("/");
                let savepicname = urlarry[urlarry.length - 1];
                let dirpath = jsb.fileUtils.getWritablePath() + 'chatimg/';
                savechatData.contentpath = arry[1] + "$" + arry[2] + "$" + dirpath + savepicname + ".jpg";
            }

            var notsendstr = JSON.stringify(savechatData)
            array.notSend.push(notsendstr);

            if (Messagedata.chat_type == ChatEnum.MessageEnum.HONGBAO) {
                array.isReceived = false;
            }

            cc.sys.localStorage.setItem(localStoragekey, JSON.stringify(array))//保存到本地
            //通知ui
            if (savechatData.originId != cc.vv.chatMgr.systermMessageoriginId || savechatData.originId != cc.vv.chatMgr.systermMessageHongBaooriginId) {  //系统消息
                if (savechatData.originId == cc.vv.session.getRid()) {
                    savechatData.rolename = cc.vv.session.getPlayer().rolename
                    savechatData.url = cc.vv.session.getPlayer().logo
                } else {
                    if (!this.TongXunLuData) {
                        this.TongXunLuData = TongXunLuData.getInstance();
                    }
                    savechatData.rolename = this.TongXunLuData.getUserData(savechatData.originId).name
                    savechatData.url = this.TongXunLuData.getUserData(savechatData.originId).url
                }
            }
            if (savechatData.contenttype == ChatEnum.MessageEnum.PICTURE) {
                cc.vv.eventCustom.emit("addChatItem", {
                    chatdata: savechatData,  //数据
                    addtop: false,           //是否添加到scroll的顶部
                    needScrolltobottom: true,//是否需要滚动到底部
                    selfPic: true,
                })
            } else {
                cc.vv.eventCustom.emit("addChatItem", {
                    chatdata: savechatData,  //数据
                    addtop: false,           //是否添加到scroll的顶部
                    needScrolltobottom: true,//是否需要滚动到底部
                })
            }

        } else {
            //存到本地存储字典
            cc.sys.localStorage.setItem(key, JSON.stringify(Messagedata))
            //从消息中获取最新的消息id
            var newid = Messagedata.id;
            var session = sessionID
            if (!flagexlude) {
                if (Messagedata.messagetype == ChatEnum.ChatTypeEnum.GROUP) {
                    cc.sys.localStorage.setItem(this.sessionGroupFront + session, JSON.stringify(newid))
                } else {
                    cc.sys.localStorage.setItem(this.sessionFront + session, JSON.stringify(newid))
                }
            }
        }
    }

    //删除某一条会话的本地记录
    clearOneSessionMessage(session, isgroup) {
        var newid = 0;
        if (isgroup) {
            newid = Number(cc.sys.localStorage.getItem(this.sessionGroupFront + session))
        } else {
            newid = Number(cc.sys.localStorage.getItem(this.sessionFront + session))
        }
        for (var s = 2; s <= newid; s++) {  //从第二条删除 ，第一条设置成失效 。考虑留一条消息保存失效或者禁言消息
            let localStoragekey = cc.vv.session.getRid() + "_" + session + "_" + s;
            if (isgroup) {
                localStoragekey = "group_" + cc.vv.session.getRid() + "_" + session + "_" + s;
            }
            cc.sys.localStorage.removeItem(localStoragekey);
        }
        //单独处理第一条消息  第一条消息设置成失效
        let localStoragekey = cc.vv.session.getRid() + "_" + session + "_" + 1;
        if (isgroup) {
            localStoragekey = "group_" + cc.vv.session.getRid() + "_" + session + "_" + 1;
        }
        var datastring = cc.sys.localStorage.getItem(localStoragekey);
        if (!datastring) return;
        var arry = JSON.parse(datastring)
        arry.state = ChatEnum.MessageState.ERROR
        cc.sys.localStorage.setItem(localStoragekey, JSON.stringify(arry))

        if (isgroup) {
            cc.sys.localStorage.removeItem(this.sessionGroupFront + session)
        } else {
            cc.sys.localStorage.removeItem(this.sessionFront + session)
        }
        this.setNewMsgNum(session, 0);
        cc.vv.eventCustom.emit("deletOneSessionSucess", { session: session, isgroup: isgroup });

        if (isgroup) {
            cc.vv.GroupDetailData.setReadedMsgId(session, 1)
        } else {
            cc.vv.TongXunLuData.setReadedMsgId(session, 1)
        }
        cc.vv.GLUtils.showTips("聊天记录删除成功！");
    }

    getNewMessageID(sessionID) {
        var session = sessionID
        return Number(cc.sys.localStorage.getItem(this.sessionFront + session))
    }
    getNewGroupMessageID(sessionID) {
        var session = sessionID
        return Number(cc.sys.localStorage.getItem(this.sessionGroupFront + session))
    }

    setsoftjianpanheight(args) {
        if (cc.sys.isNative) {
            if (cc.sys.os == cc.sys.OS_IOS) {
                var arry = args[0].split("_");
                var height = (cc.view.getFrameSize().height / arry[1]) * arry[0];
                this._softkeyoffy = Math.floor(height * (cc.winSize.height / cc.view.getFrameSize().height))
                cc.sys.localStorage.setItem("softkeyboard", String(this._softkeyoffy))
                cc.sys.localStorage.setItem("softkeyboardreal", String(arry[0]))
                console.log("ios 设置软键盘高度height is", height)
                //临时修改bug  这里本来应该在原生端处理 这里临时处理
                cc.vv.eventCustom.emit("openjianpan");
            }
            else {
                var height = Number(args[0]);
                this._softkeyoffy = Math.floor(height * (cc.winSize.height / cc.view.getFrameSize().height))
                cc.sys.localStorage.setItem("softkeyboard", String(this._softkeyoffy))
                cc.sys.localStorage.setItem("softkeyboardreal", String(height))
                console.log("andriod 设置软键盘高度height is", height)
            }
        }
    }

    getsoftkeyoffy() {
        return Number(cc.sys.localStorage.getItem("softkeyboard") || 0)
    }
    zhuanfaMessage(data) {
        this.zhuanfadata = data[0]
    }

    gettimeStr(time, currenttime) {
        var returntime = "";
        var chattime = cc.vv.GLUtils.formatDate(time)
        var timelbwidth = this.shorttimewidth;
        var timelingdian = Date.parse(cc.vv.GLUtils.formatDate(currenttime).split(" ")[0] + " 0:0:0") //当天凌晨
        if (time - timelingdian >= 0) {  //今天
            if (time - timelingdian < 12 * 3600 * 1000) { // 今天上午
                returntime = "上午 " + chattime.split(" ")[1]
            } else {// 今天下午
                returntime = "下午 " + chattime.split(" ")[1]
            }
        } else if (time - timelingdian < 0 && time - timelingdian >= 0 - 24 * 3600 * 1000) {//昨天
            returntime = "昨天"
            timelbwidth = this.shorttimewidth / 2;
        } else if (time - timelingdian < 0 - 24 * 3600 * 1000 && time - timelingdian >= 0 - 48 * 3600 * 1000) {//前天
            timelbwidth = this.shorttimewidth / 2;
            returntime = "前天"
        } else {  //前天之前
            returntime = chattime.split(" ")[0]
        }
        return {
            chattime: returntime,
            timelbwidth: timelbwidth
        }
    }
    private logout() {
        this.resetMsgNum();
        this.clearAllTimer();
    }
    private clearAllTimer() {
        this.messagedataqueue = [];  //优先队列
        this.LoadOfflineMsgOver = 1;
        if (this.startLoadOfflineMsgTimer) {
            clearInterval(this.startLoadOfflineMsgTimer);
            this.startLoadOfflineMsgTimer = null;
        }
    }
    private resetMsgNum() {
        this.newMsgNum = 0;
        this.newMsgData = {};
    }
    private setAllNewMsgNum(num: number) {
        if (num == null || num == void 0) return false;
        num < 0 && (num = 0);
        this.newMsgNum = num;
        return true;
    }
    public getAllNewMsgNum() {
        return this.newMsgNum;
    }
    public getNewMsgNum(Id: number) {
        return this.newMsgData[Id];
    }
    public setNewMsgNum(Id: number, num: number) {
        if (num == null || num == void 0) return false;
        num < 0 && (num = 0);
        let newMsgNum = this.newMsgData[Id];
        newMsgNum || (newMsgNum = 0);
        this.newMsgData[Id] = num;
        let addNum = num - newMsgNum;
        let allNewMsgNum = this.getAllNewMsgNum();
        allNewMsgNum += addNum;
        this.setAllNewMsgNum(allNewMsgNum);
        cc.vv.eventCustom.emit('updateNewReqNum');
        return true;
    }
    //更新客服聊天玩家信息
    //更新索引  更新具体索引指向的rid数据
    public updateServiceRid(rid: number, name: string, headurl: string, type: number) {
        let ServiceArry = cc.sys.localStorage.getItem(this.serviceArryKey);  //存储的是客服聊天的玩家索引
        let ret = [];
        if (ServiceArry) {
            ret = JSON.parse(ServiceArry);
        }
        // let temp = {
        //     rid: rid,
        //     name: name,
        //     url: "" || headurl,
        // }
        if (type) {
            let temp = {
                rid: rid,
                name: name,
                url: "" || headurl,
                type: type,
            }
            cc.sys.localStorage.setItem(this.servicePlayerKey + rid, JSON.stringify(temp))
        } else {
            let temp = {
                rid: rid,
                name: name,
                url: "" || headurl,
            }
            cc.sys.localStorage.setItem(this.servicePlayerKey + rid, JSON.stringify(temp))
        }

        //如果已经存储的有  不更新索引
        if (ret.length > 0) {
            for (let t = 0; t < ret.length; t++) {
                if (ret[t] == rid) {
                    return;
                }
            }
        }
        //如果存储的没有  添加玩家到索引中
        ret.push(rid);
        let str = JSON.stringify(ret)
        cc.sys.localStorage.setItem(this.serviceArryKey, str);
    }
    public GetServiceIdArr() {
        let ServiceArry = cc.sys.localStorage.getItem(this.serviceArryKey);
        let ret = [];
        if (ServiceArry) {
            ret = JSON.parse(ServiceArry);
        }
        return ret;
    }
    public ClearAllServiceMsg() {
        let serviceIdArr = this.GetServiceIdArr();
        if (serviceIdArr.length == 0) return false;
        for (let i in serviceIdArr) {
            let id = serviceIdArr[i];
            this.clearOneSessionMessage(id, false);
        }
        return true;
    }
    public NewMsgAlert(data: any) {
        if (!data) return false;
        let isDontBother = data.isDontBother;
        let localValue: any = cc.sys.localStorage.getItem(GCtrl.dataConfig.VOICE_VIBRATION_KEY);
        let obj = { voice: GCtrl.dataConfig.VOICE_STATE.ON, vibration: GCtrl.dataConfig.VIBRATION_STATE.ON };
        localValue = localValue ? JSON.parse(localValue) : obj;
        let voice_state = localValue.voice;
        let vibration_state = localValue.vibration;
        let alert = '';
        let v = 0;
        let b = 0;
        v = voice_state == GCtrl.dataConfig.VOICE_STATE.ON ? 1 : 0;
        b = vibration_state == GCtrl.dataConfig.VIBRATION_STATE.ON ? 1 : 0;
        isDontBother && (v = 0, b = 0);
        alert = `${v}.${b}`;
        // cc.vv.GLSDKMgr.NewMsgAlert(alert);
        return true;
    }
    public getNewStr(friendid, chatdata) {
        let str = "";
        if (friendid == ChatEnum.SystemNotice_ID) {
            str = JSON.parse(chatdata.content).data.slice(0, 15) + "...."
        } else if (friendid == ChatEnum.MoneyChange_ID) { // 时光支付
            if (chatdata.contenttype == ChatEnum.DataTypeEnum.GAMEBILL) // 时光支付中的战绩 和聊天中的战绩 ui不一样
            {
                let temp = JSON.parse(chatdata.content);
                let strtemp = "支付："
                if (temp.paind_coin > 0) {
                    strtemp = "收款："
                }
                if (temp.club_name) {
                    str = "你在" + temp.club_name + "中的【" + cc.vv.GLDefine.getChineseNameById(temp.gameid) + "】游戏中已成功" + str + cc.vv.GLUtils.getExchangeCoinNum(Math.abs(temp.paind_coin)) + "元。"
                } else {
                    str = "你在【" + cc.vv.GLDefine.getChineseNameById(temp.gameid) + "】游戏中已成功" + str + cc.vv.GLUtils.getExchangeCoinNum(Math.abs(temp.paind_coin)) + "元。"
                }
                // str = "你在" + temp.club_name + "中的【" + cc.vv.GLDefine.getChineseNameById(temp.gameid) + "】游戏中已成功" + str + cc.vv.GLUtils.getExchangeCoinNum(Math.abs(temp.paind_coin)) + "元。"
            }
            else if (chatdata.contenttype == ChatEnum.DataTypeEnum.RECHARGE) {
                str = "你收到了一条充值订单信息";
            }
            else if (chatdata.contenttype == ChatEnum.DataTypeEnum.WITHDRAW) {
                str = "你收到了一条提现订单信息";
            }
        }
        else if (friendid == ChatEnum.GameStart_ID) {  //时光游戏
            let temp = JSON.parse(chatdata.content);
            if (temp.club_name) {
                str = "你在" + temp.club_name + "中的游戏【" + cc.vv.GLDefine.getChineseNameById(temp.gameid) + "】开始了。请尽快进入游戏！"
            } else {
                str = "游戏【" + cc.vv.GLDefine.getChineseNameById(temp.gameid) + "】开始了。请尽快进入游戏！"
            }
        } else {
            str = chatdata.content
            if (chatdata.contenttype == ChatEnum.MessageEnum.EFT) {  //转账信息
                var tempdata = JSON.parse(chatdata.content)
                str = "[转账]" + "你收到一条转账消息"//tempdata.text + tempdata.coin / 100
            }
            if (chatdata.contenttype == ChatEnum.MessageEnum.HONGBAO) {  //红包信息
                str = "你收到了一个红包";
            }
            if (chatdata.contenttype == ChatEnum.DataTypeEnum.GAMEINVITE) { //邀请消息
                str = "你收到了一条游戏邀请信息"
            }
            if (chatdata.contenttype == ChatEnum.DataTypeEnum.GAMEBILL) { //邀请消息
                str = "你收到了一条战绩信息"
            }
            if (chatdata.contenttype == ChatEnum.MessageEnum.PICTURE) {  //图片消息
                str = "[图片]" + "你收到一张图片消息"//tempdata.text + tempdata.coin / 100
            }
            if (chatdata.originId == cc.vv.chatMgr.systermMessageHongBaooriginId) {
                let jsondata = JSON.parse(chatdata.content);
                let sendplayerid = jsondata.sender
                let recvplayerid = jsondata.receiver
                if (chatdata.group || chatdata.frienddata.group) {  //群聊
                    let id = chatdata.Id || chatdata.frienddata.Id;
                    var palyerdata = cc.vv.GroupDetailData.getGroupData(id).groupAllMemberDataArr[recvplayerid]
                    if (!palyerdata) {
                        palyerdata = cc.vv.GroupDetailData.getGroupData(id).diedMemberData[recvplayerid]
                    }
                }
                else {  //私聊
                    palyerdata = cc.vv.TongXunLuData.getUserData(sendplayerid)
                }
                if (sendplayerid == cc.vv.session.getRid()) {
                    str = palyerdata.name + "领取了你的红包";
                } else {
                    str = palyerdata.name + "领取了红包";
                }
                str = str.slice(0, 15) + "...."
            }
        }
        return str;
    }
}
export let charDataMgr: ChatDataMgr = new ChatDataMgr();
